<template>
	<view class="container">
		<view class="head">
			<view class="head_li">
				<view class="_img">
					<image :src="myInfo.avatar" @click="NavigatorPersonal()"></image>
					<text>{{myInfo.nickName}}</text>
				</view>
				<uni-icons class="icon" type="plusempty" size="28" color="#fff" @click="menu"></uni-icons>
			</view>
		</view>
		<up-overlay :show="show" @click="show = false" zIndex="1" opacity="0.1"></up-overlay>
		<view class="head_menu" v-show="show">
			<view class="item" v-for="(item,i) in icons" :key="i" @click="NavigatorMenu(i)">
				<image :src="item.src"></image>
				<text>{{item.name}}</text>
			</view>
		</view>
		<scroll-view :scroll-y="scroll" class="body" @touchstart="touchStart" @touchmove="touchMove"
			@touchend="touchEnd" scroll-with-animation="true" @scroll="Scroll">
			<view class="refresh" v-show="refresh">
				<!-- <image src="/static/chat-icons/refeash.png"></image> -->
				<image src="/static/chat-icons/refreash.png"></image>
			</view>
			<view class="middle">
				<view class="search" @click="NavigatorSearch">
					<up-icon name="search" size="28" color="#b6b6b6"></up-icon>
					<text>薛之谦</text>
				</view>
			</view>
			<view class="msg_body">
				<uni-swipe-action>
					<view v-for="(item,i) in topList" :key="i">
						<view class="pop" v-show="(i == topPopIndex)">
							<view class="one" @click.stop="updateMsg('delete',i,'top')">删除</view>
							<view class="two" @click.stop="updateMsg('read',i,'top')">标记已读</view>
							<view class="tre" @click.stop="updateMsg('top',i,'top')">取消置顶</view>
						</view>
						<up-overlay :show="(topPopIndex != null)" opacity="0" zIndex="1"
							@click="topPopIndex = null"></up-overlay>
						<uni-swipe-action-item :right-options="toping" @click="onTopClick($event,i)" @touchstart="Slide"
							@touchmove="SlideMove" @touchend="SildEnd($event,i,'top')" @change="swipeChange($event, i)"
							:show="active ? '':'none'">
							<view class="mag_top_item" @click="Navigator(item)">
								<image :src="item.avatar" class="_img"></image>
								<view class="mide">
									<text class="name">{{item.nickName}}</text>
									<text class="msg">{{truncateString(item.lastMessage,18)}}</text>
								</view>
								<view class="time">
									<text>{{this.formatDateTime(item.lastMessageTime)}}</text>
									<view class="badge" v-show="(item.badge != 0)"><text>{{(item.badge > 99 ? '99+':item.badge)}}</text></view>
								</view>
							</view>
						</uni-swipe-action-item>
					</view>
					<view v-for="(item,i) in msgList" :key="i">
						<view class="pop" v-show="(i == popIndex)">
							<view class="one" @click.stop="updateMsg('delete',i,'msg')">删除</view>
							<view class="two" @click.stop="updateMsg('read',i,'msg')">标记已读</view>
							<view class="tre" @click.stop="updateMsg('top',i,'msg')">置顶</view>
						</view>
						<up-overlay :show="(popIndex != null)" opacity="0" zIndex="1"
							@click="popIndex = null"></up-overlay>
						<uni-swipe-action-item :right-options="options" @click="onClick($event,i)" @touchstart="Slide"
							@touchmove="SlideMove" @touchend="SildEnd($event,i,'msg')" @change="swipeChange($event, i)"
							:show="active ? '':'none'">
							<view class="mag_item" @click="Navigator(item)">
								<image :src="item.avatar" class="_img"></image>
								<view class="mide">
									<text class="name">{{item.nickName}}</text>
									<text class="msg">{{truncateString(item.lastMessage,18)}}</text>
								</view>
								<view class="time">
									<text>{{this.formatDateTime(item.lastMessageTime)}}</text>
									<view class="badge" v-show="(item.badge != 0)"><text>{{(item.badge > 99 ? '99+':item.badge)}}</text></view>
								</view>
							</view>
						</uni-swipe-action-item>
					</view>
				</uni-swipe-action>
			</view>
		</scroll-view>
		<my-tabBar :routePath="$page.path"></my-tabBar>
	</view>
</template>

<script>
	import {
		mapState,
		mapMutations,
	} from 'vuex'
	import {
		refreash,
		clearRead,setTop,setCancelTop,deleteConversation
	} from '../../common/api';
	export default {
		computed: {
			...mapState('info', ['myInfo'])
		},
		data() {
			return {
				show: false,
				active: true,
				scroll: true,
				scrollTop: 0,
				startY: 0, // 触摸开始时的X坐标
				startX: 0,
				moveY: 0, // 触摸点移动的距离
				moveBy: 0,
				SildeTime: 0, //按住时间
				refresh: false, //刷新
				isoption: false, //侧滑操作中
				swipe_action: false, //阻止事件传递
				popIndex: null, //弹窗索引
				topPopIndex: null, //弹窗索引
				options: [{
						text: '置顶',
						style: {
							backgroundColor: '#0894ff'
						}
					},
					{
						text: '标记已读',
						style: {
							backgroundColor: '#ffc106'
						}
					},
					{
						text: '删除',
						style: {
							backgroundColor: '#ff340c'
						},
					}
				],
				toping: [{
						text: '取消置顶',
						style: {
							backgroundColor: '#0894ff'
						}
					},
					{
						text: '标记未读',
						style: {
							backgroundColor: '#ffc106'
						}
					},
					{
						text: '删除',
						style: {
							backgroundColor: '#ff340c'
						}
					},
				],
				topList: [],
				icons: [{
						src: '/static/message-icons/Create_group_chat.png',
						name: '创建群聊'
					},
					{
						src: '/static/message-icons/Add_friends.png',
						name: '加好友/群'
					},
					{
						src: '/static/message-icons/Scan_it.png',
						name: '扫一扫'
					}
				],
				msgList: []
			};
		},
		onLoad(val) {
			this.Refreash();
			uni.hideTabBar();
		},
		onShow() {
		    this.Refreash();
		},
		methods: {
			truncateString(str, maxLength) {
				if (maxLength > 0 && typeof str === 'string') {
					if (str.length <= maxLength) {
						return str;
					} else {
						return str.substring(0, maxLength) + '...';
					}
				}
				return str;
			},
			onClick(e, index) {
				this.isoption = true
				let data = {userId:this.myInfo.id,cId:this.msgList[index].cid}
				if (e.index === 0) {
					setTop(data)
					this.topList.unshift(this.msgList[index]);
					this.msgList.splice(index, 1);
				}
				if (e.index === 1) {
					if (this.msgList[index].badge != 0) {
						clearRead(data)
						this.msgList[index].badge = 0;
					}
				}
				if (e.index === 2) {
					deleteConversation(data)
					this.msgList.splice(index, 1);
				}
				this.active = false
				setTimeout(() => {
					this.isoption = false
				}, 500);
			},
			onTopClick(e, index) {
				this.isoption = true
				let data = {userId:this.myInfo.id,cId:this.topList[index].cid}
				if (e.index === 0) {
					setCancelTop(data)
					this.msgList.unshift(this.topList[index]);
					this.topList.splice(index, 1);
				}
				if (e.index === 1) {
					if (this.msgList[index].badge != 0) {
						clearRead(data)
						this.msgList[index].badge = 0;
					}
				}
				if (e.index === 2) {
					deleteConversation(data)
					this.topList.splice(index, 1);
				}
				this.active = false
				setTimeout(() => {
					this.isoption = false
				}, 500);
			},
			swipeChange(e, index) {
				if (e == 'right') {
					this.scroll = false;
				} else {
					this.swipe_action = true;
					this.scroll = true;
				}
				setTimeout(() => {
					this.swipe_action = false;
				}, 100);
				this.active = true
			},
			menu() {
				this.show = !this.show
			},
			NavigatorMenu(i) {
				this.show = false;
				if (i == 1) {
					uni.navigateTo({
						url: '/subpkg/addFriend_search/addFriend_search?uid='+this.myInfo.id
					})
				}
			},
			Navigator(item) {
				if (this.SildeTime >= 300) return;
				if (this.isoption || this.swipe_action) return;
				if (item.badge != 0) {
					clearRead({
						userId: this.myInfo.id,
						cId: item.cid
					})
					item.badge = 0;
				}
				uni.navigateTo({
					url: '/subpkg/chat_interface/chat_interface?cId='+item.cid+'&nickName='+item.nickName
				})
			},
			NavigatorPersonal() {
				uni.navigateTo({
					url: '/subpkg/personal_details/personal_details?fid=' + this.myInfo.id
				})
			},
			NavigatorSearch() {
				uni.navigateTo({
					url: '/subpkg/head_search/head_search'
				})
			},
			Scroll(e) {
				this.scrollTop = e.detail.scrollTop;
			},
			Slide(e) {
				this.SildeTime = e.timeStamp
				this.startX = e.touches[0].clientX;
			},
			SlideMove(e) {
				let moveX = e.touches[0].clientX - this.startX;
				if (moveX >= 100 || moveX <= -100) {
					this.moveY = 0;
					this.scroll = false;
					this.dragging = false;
				}
				this.scroll = true;
			},
			SildEnd(e, i, val) {
				this.SildeTime = e.timeStamp - this.SildeTime;
				if (!this.scroll) return;
				if (this.SildeTime >= 300) {
					if (val == 'msg') {
						setTimeout(() => {
							this.popIndex = i
						}, 100);
						return
					}
					if (val == 'top') {
						setTimeout(() => {
							this.topPopIndex = i
						}, 100);
						return
					}
				}
			},
			updateMsg(val, i, mode) {
				let data = {userId:this.myInfo.id,cId:this.msgList[index].cid}
				if (mode == 'msg') {
					this.popIndex = null;
					if (val == 'delete') {
						deleteConversation(data)
						this.msgList.splice(i, 1);
					}
					if (val == 'read') {
						clearRead(data)
						this.msgList[i].badge = 0;
					}
					if (val == 'top') {
						setTop(data)
						this.topList.unshift(this.msgList[i]);
						this.msgList.splice(i, 1);
					}
				} else {
					this.topPopIndex = null;
					if (val == 'delete') {
						deleteConversation(data)
						this.topList.splice(i, 1);
					}
					if (val == 'read') {
						clearRead(data)
						this.topList[i].badge = 0;
					}
					if (val == 'top') {
						setTop(data)
						this.msgList.unshift(this.topList[i]);
						this.topList.splice(i, 1);
					}
				}

			},
			Refreash() {
				this.scroll = false;
				refreash({
					userId: this.myInfo.id
				}).then((res) => {
					if (res) {
						let data = res.data;
						this.msgList = data.list.sort((a, b) => new Date(b.lastMessageTime) - new Date(a.lastMessageTime));
						this.topList = data.topList.sort((a, b) => new Date(b.lastMessageTime) - new Date(a.lastMessageTime));
					}
				})
				setTimeout(() => {
					this.scroll = true;
					this.refresh = false;
				}, 2000);
			},
			touchStart(event) {
				if (this.scrollTop != 0) return
				this.startY = event.touches[0].clientY - this.moveY;
				if (!this.scroll || this.refresh) return
				this.dragging = true; // 开始拖动
			},
			touchMove(event) {
				this.scroll = false
				if (this.dragging) {
					event.preventDefault(); // 防止滚动
					let moveY = event.touches[0].clientY - this.startY;
					moveY = moveY < 0 ? 0 : moveY
					this.moveY = moveY;
				}
			},
			touchEnd() {
				this.dragging = false; // 结束拖动
				if (this.moveY >= 100) {
					this.moveY = 0;
					this.refresh = true;
					this.Refreash();
				}
				this.moveY = 0;
				this.scroll = true;
			},
			formatDateTime(dateString) {
				// 解析日期字符串为Date对象
				const inputDate = new Date(dateString);

				// 获取今天是周几（0 = 星期日，1 = 星期一，...，6 = 星期六）
				const today = new Date();
				today.setHours(0, 0, 0, 0); // 重置时间部分，以便比较日期

				// 获取当前年份
				const currentYear = today.getFullYear();
				const inputYear = inputDate.getFullYear();

				// 设置星期数组
				const daysOfWeek = ["星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"];

				// 计算输入日期与今天相差的天数
				const diffTime = today - inputDate;
				const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));

				// 获取输入日期的月份和日期
				const month = (inputDate.getMonth() + 1).toString().padStart(2, '0'); // 月份，需要+1因为getMonth()是从0开始计数
				const day = inputDate.getDate().toString().padStart(2, '0');

				let result;

				if (diffDays === 0) {
					// 今天
					result = `${inputDate.getHours()}:${String(inputDate.getMinutes()).padStart(2, '0')}`;
				} else if (diffDays === 1) {
					// 昨天
					result = `昨天 ${inputDate.getHours()}:${inputDate.getMinutes()}`;
				} else if (diffDays === 2) {
					// 前天
					result = `前天 ${inputDate.getHours()}:${inputDate.getMinutes()}`;
				} else if (diffDays < 7) {
					// 超过昨天但在一周之内
					result = daysOfWeek[inputDate.getDay()];
				} else if (inputYear === currentYear) {
					// 今年但不在一周内
					result = `${month}-${day}`;
				} else {
					// 超出一年范围
					result = `${inputYear.toString().substring(2)}/${month}/${day}`;
				}
				return result;
			}
		},
		watch: {
			moveY(newVal) {
				this.moveBy = newVal + 'rpx'
			},
		}
	}
</script>

<style lang="scss" scoped>
	.container {
		height: 100vh;
		overflow: auto;

		.head {
			background: linear-gradient(90deg, rgba(122, 220, 241, 1) 0%, rgba(43, 163, 242, 1) 48%);
			width: 750rpx;
			height: 150rpx;
			position: relative;

			.head_li {
				position: absolute;
				bottom: 0;
				width: 750rpx;
				height: 130rpx;
				display: flex;
				justify-content: space-between;
				line-height: 160rpx;
				padding: 0 0rpx;

				._img {
					width: 250rpx;
					height: 90rpx;
					padding: 10rpx;
					display: flex;

					image {
						width: 80rpx;
						height: 80rpx;
						border-radius: 50rpx;
						margin-top: 25rpx;
						margin-left: 10rpx;

						&:active {
							transform: scale(0.9);
							transition: transform 0.1s;
						}
					}

					text {
						color: #fff;
						font-size: 30rpx;
						opacity: 0.8;
						padding: 10rpx 20rpx;
						display: flex;
						line-height: 85rpx;
					}
				}

				.icon {
					padding: 0 30rpx;

					&:active {
						transform: scale(0.8);
						transition: transform 0.1s;
					}
				}
			}
		}


		.head_menu {
			position: absolute;
			background-color: #fafafa;
			top: 50rpx;
			right: -40rpx;
			height: 300rpx;
			width: 300rpx;
			padding: 10rpx;
			border-radius: 20rpx;
			z-index: 2;
			animation: scale 0.1s linear 1 forwards;
			transform: scale(0.5);

			.item {
				height: 100rpx;
				display: flex;
				align-items: center;

				image {
					width: 50rpx;
					height: 50rpx;
					padding: 0 20rpx 0 40rpx;
				}

				text {
					font-size: 30rpx;
				}

				&:active {
					background-color: rgba(214, 214, 214, 0.6);
					transition: background-color 0.2s;
				}
			}

			@keyframes scale {
				to {
					transform: scale(1);
					position: absolute;
					top: 180rpx;
					right: 10rpx;
				}
			}

			&:after {
				content: "";
				display: block;
				border-width: 15px;
				position: absolute;
				top: -30rpx;
				right: 30rpx;
				border-style: solid dashed dashed solid;
				border-color: transparent transparent #fafafa transparent;
				font-size: 0;
				line-height: 0;
			}

			&:after {
				top: -28px;
				border-color: transparent transparent #fafafa transparent;
			}
		}

		.body {
			width: 750rpx;
			height: 84vh;
			background-color: #e9e9e9;
			transform: translateY(v-bind(moveBy));

			.refresh {
				height: 120rpx;
				display: flex;
				justify-content: center;
				align-items: center;
				background-color: #fff;

				image {
					width: 80rpx;
					height: 80rpx;
					transform: rotate(360deg);
					animation: rotate 3s linear infinite;

					@keyframes rotate {
						from {
							transform: rotate(0deg);
						}

						to {
							transform: rotate(360deg);
						}
					}
				}
			}

			.middle {
				height: 110rpx;
				display: flex;
				justify-content: center;
				align-items: center;

				.search {
					width: 700rpx;
					height: 80rpx;
					display: flex;
					justify-content: center;
					align-items: center;
					border-radius: 20rpx;
					background-color: #fff;

					text {
						color: #b6b6b6;
					}
				}
			}

			.msg_body {
				height: 77vh;

				.pop {
					min-width: 340rpx;
					height: 70rpx;
					display: flex;
					justify-content: space-between;
					background-color: #404040;
					color: #e4e4e4;
					position: absolute;
					left: 220rpx;
					margin-top: -50rpx;
					border-radius: 20rpx;
					z-index: 2;
					font-size: 25rpx;

					%opo {
						display: flex;
						justify-content: center;
						align-items: center;
						border-radius: 10rpx
					}

					.one {
						@extend %opo;
						width: 85rpx;
					}

					.two {
						@extend %opo;
						border-radius: 0;
						width: 130rpx;
					}

					.tre {
						@extend %opo;
						min-width: 85rpx;
					}

					:active {
						background-color: #949494;
					}

					&:after {
						content: "";
						display: block;
						border-width: 12px;
						position: absolute;
						top: 0rpx;
						right: 140rpx;
						border-style: solid dashed dashed solid;
						border-color: #404040 transparent transparent transparent;
						font-size: 0;
						line-height: 0;
						z-index: 2;
					}

					&:after {
						top: 36px;
						border-color: #404040 transparent transparent transparent;
						z-index: 2;
					}
				}

				.mag_top_item {
					height: 125rpx;
					display: flex;
					justify-content: space-between;
					align-items: center;
					padding: 10rpx 0;
					background-color: #e9e9e9;

					&:active {
						background-color: #d6d6d6;
						transition: background-color 0.2s;
					}
				}

				.mag_item {
					height: 125rpx;
					display: flex;
					justify-content: space-between;
					align-items: center;
					padding: 10rpx 0;
					background-color: #fafafa;

					&:active {
						background-color: #d6d6d6;
						transition: background-color 0.2s;
					}
				}

				._img {
					width: 100rpx;
					height: 100rpx;
					border-radius: 50rpx;
					margin-left: 15rpx;
				}

				.mide {
					width: 450rpx;
					display: flex;
					flex-direction: column;

					.name {
						color: #000;
						font-size: 35rpx;
						font-weight: bold;
						padding: 0 0 10rpx;
					}

					.msg {
						color: #b6b6b6;
						font-size: 25rpx;
					}
				}

				.time {
					height: 100rpx;
					width: 150rpx;
					position: relative;
					padding: 5rpx 0;

					text {
						display: flex;
						justify-content: end;
						margin-right: 10rpx;
						color: #b6b6b6;
						font-size: 28rpx;
					}

					.badge {
						position: absolute;
						right: 10rpx;
						bottom: 5rpx;
						// background-color: #cecece;
						background-color: #e93a00;
						border-radius: 100rpx;

						text {
							color: #fff;
							font-size: 20rpx;
							font-weight: bold;
							margin: 5rpx 15rpx;
						}
					}
				}
			}
		}
	}
</style>